package com.newway.back.controller.approval;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.back.dto.approval.ApprovalTaskDto;
import com.newway.back.entity.approval.ApprovalInstance;
import com.newway.back.entity.approval.ApprovalNode;
import com.newway.back.entity.approval.ApprovalRecord;
import com.newway.back.entity.approval.ApprovalTask;
import com.newway.back.enums.ApprovalActionEnum;
import com.newway.back.enums.ApprovalStatusEnum;
import com.newway.back.enums.TaskStatusEnum;
import com.newway.back.mapper.approval.ApprovalInstanceMapper;
import com.newway.back.mapper.approval.ApprovalNodeMapper;
import com.newway.back.mapper.approval.ApprovalRecordMapper;
import com.newway.back.mapper.approval.ApprovalTaskMapper;
import com.newway.back.service.impl.ApprovalCommonService;
import com.newway.back.util.SecurityUserContext;
import com.newway.common.Result;
import com.newway.exception.BusinessException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/back/approval/task")
@RestController
public class ApprovalTaskController {

    @Resource
    ApprovalRecordMapper approvalRecordMapper;

    @Resource
    ApprovalTaskMapper approvalTaskMapper;

    @Resource
    ApprovalNodeMapper approvalNodeMapper;

    @Resource
    ApprovalInstanceMapper approvalInstanceMapper;

    @Resource
    ApprovalCommonService approvalCommonService;

    @GetMapping("/list")
    public Result getTaskList(){
        QueryWrapper<ApprovalTask> approvalTaskQueryWrapper = new QueryWrapper<>();
        approvalTaskQueryWrapper.eq("approver_id",SecurityUserContext.getCurrentUserInfo().getId());
        approvalTaskQueryWrapper.eq("status",TaskStatusEnum.PENDING.getValue());
        List<ApprovalTask> approvalTasks = approvalTaskMapper.selectList(approvalTaskQueryWrapper);
        return Result.success(approvalTasks);
    }

    @PostMapping("/dealWith")
    @Transactional
    public Result approvalTask(@RequestBody ApprovalTaskDto approvalTaskDto){
        ApprovalTask approvalTask = approvalTaskMapper.selectById(approvalTaskDto.getTaskId());
        if(approvalTask == null){
            throw new BusinessException("当前任务不存在，请刷新重试");
        }
        QueryWrapper<ApprovalRecord> approvalRecordQueryWrapper = new QueryWrapper<>();
        approvalRecordQueryWrapper.eq("instance_id",approvalTask.getInstanceId());
        approvalRecordQueryWrapper.eq("node_id",approvalTask.getNodeId());
        //TODO 记录表是否加上taskId
        ApprovalRecord approvalRecord = approvalRecordMapper.selectOne(approvalRecordQueryWrapper);
        if(approvalRecord!=null){
            throw new BusinessException("当前任务已被审批，请刷新重试");
        }
        if("1".equals(approvalTaskDto.getResult())){
            agreeResult(approvalTaskDto,approvalTask);
        }else{
            rejectResult(approvalTaskDto,approvalTask);
        }
        return Result.success();
    }

    private void agreeResult(ApprovalTaskDto approvalTaskDto,ApprovalTask approvalTask) {
        ApprovalNode nextNode= approvalCommonService.handleNextNode(approvalTask);
        ApprovalInstance approvalInstance = approvalInstanceMapper.selectById(approvalTask.getInstanceId());
        //没有下一级了
        if(nextNode==null){
            approvalInstance.setCurrentStatus(ApprovalStatusEnum.APPROVED.getValue());
            approvalInstanceMapper.updateById(approvalInstance);
        }else{
            // 3. 确定审批人
            Integer approverId = approvalCommonService.determineApprover(nextNode);
            //还存在下一级
            ApprovalTask nextTask = new ApprovalTask();
            nextTask.setInstanceId(approvalInstance.getInstanceId());
            nextTask.setNodeId(nextNode.getNodeId());
            nextTask.setApproverId(approverId);
            nextTask.setStatus(TaskStatusEnum.PENDING.getValue());
            approvalTaskMapper.insert(nextTask);
            // 5. 更新实例当前节点
            approvalInstance.setCurrentNodeId(nextNode.getNodeId());
            approvalInstanceMapper.updateById(approvalInstance);
        }
        //处理当前数据
        approvalTask.setStatus(TaskStatusEnum.APPROVED.getValue());
        approvalTask.setProcessedAt(LocalDateTime.now());
        approvalTaskMapper.updateById(approvalTask);
        //处理该条记录 在其他人的代办数据 TODO
        //历史入库
        ApprovalRecord record = new ApprovalRecord();
        record.setApproverId(SecurityUserContext.getCurrentUserInfo().getId());
        record.setAction(ApprovalActionEnum.APPROVED.getValue());
        record.setInstanceId(approvalInstance.getInstanceId());
        record.setNodeId(approvalTask.getNodeId());
        record.setCreatedAt(LocalDateTime.now());
        record.setComment(approvalTaskDto.getRemarks());
        approvalRecordMapper.insert(record);
    }

    private void rejectResult(ApprovalTaskDto approvalTaskDto,ApprovalTask approvalTask) {
        ApprovalInstance approvalInstance = approvalInstanceMapper.selectById(approvalTask.getInstanceId());
        approvalInstance.setCurrentStatus(ApprovalStatusEnum.REJECTED.getValue());
        approvalInstanceMapper.updateById(approvalInstance);
        approvalTask.setStatus(TaskStatusEnum.REJECTED.getValue());
        approvalTask.setProcessedAt(LocalDateTime.now());
        approvalTaskMapper.updateById(approvalTask);
        //处理该条记录 在其他人的代办数据 TODO
        //历史入库
        ApprovalRecord record = new ApprovalRecord();
        record.setApproverId(SecurityUserContext.getCurrentUserInfo().getId());
        record.setAction(ApprovalActionEnum.APPROVED.getValue());
        record.setInstanceId(approvalInstance.getInstanceId());
        record.setNodeId(approvalTask.getNodeId());
        record.setCreatedAt(LocalDateTime.now());
        record.setComment(approvalTaskDto.getRemarks());
        approvalRecordMapper.insert(record);
    }


}
